import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;

/**
 * Created by Анастасия on 07.06.2014.
 */
public class Server {

    public static void main(String[] arg) throws IOException {
        ServerSocket serv = new ServerSocket(4454);
        File my_file = new File("C:\\Users\\Анастасия\\IdeaProjects\\Server\\Save\\HeyJava1.txt");
        Socket socket = serv.accept();

        DataInputStream z = new DataInputStream(socket.getInputStream());
        BufferedOutputStream tofile = new BufferedOutputStream(new FileOutputStream(my_file));
        long file_length;
        file_length = z.readLong();
        byte[] my_byte = new byte[(int)file_length];
        ArrayList<Byte> my_byte_list = new ArrayList<Byte>();

        int total = my_byte_list.size();
        int length;
        int n=0;

        while (total != 0) {
            length = z.read();
            System.out.println(length);
            if (length != -1) {
                z.read(my_byte, 0, length);
                for (int i =0; i != my_byte.length; i++){
                    my_byte_list.add(my_byte[i]);
                }
                n = n + length;
                total = total - length;
            } else break;
        }

        System.out.println("Hello");
        for(int i = 0; i != my_byte_list.size(); i++) {
            tofile.write(my_byte_list.get(i));
        }

        tofile.flush();
        tofile.close();
        z.close();
        socket.close();

    }

}
